package pac

import (
	"fmt"
	"io"
	"slgw_web/serial/util"
	"time"

	"github.com/jacobsa/go-serial/serial"
	models "openzbox.com/frame/echo/models/sl_gw01"
)

func OpenUart(sb models.DeviceInfo) (port io.ReadWriteCloser, error bool) {
	if sb.BAD == nil {
		util.Error("设备名称：" + sb.Name + " dtu串口连接失败,波特率BAD不能为空")
		error = true
		return
	} else if sb.DAB == nil {
		util.Error("设备名称：" + sb.Name + " dtu串口连接失败,数据位DAB不能为空")
		error = true
		return
	} else if sb.CHC == nil {
		util.Error("设备名称：" + sb.Name + " dtu串口连接失败,校验方式CHC不能为空")
		error = true
		return
	} else if sb.STO == nil {
		util.Error("设备名称：" + sb.Name + " dtu串口连接失败,停止位STO不能为空")
		error = true
		return
	} else if sb.ComName == nil {
		util.Error("设备名称：" + sb.Name + " dtu串口连接失败,串口名称ComName不能为空")
		error = true
		return
	}
	options := serial.OpenOptions{
		BaudRate:              *sb.BAD,
		DataBits:              *sb.DAB,
		StopBits:              *sb.STO,
		InterCharacterTimeout: 100,
		PortName:              *sb.ComName,
		ParityMode:            serial.ParityMode(*sb.CHC),
		MinimumReadSize:       0,
	} //初始化结构体变量
	port, err := serial.Open(options)
	if err != nil {
		error = true //失败
		util.Error("设备名称：" + sb.Name + ",dtu串口连接失败,原因：" + err.Error())
		return
	}
	for i, item := range util.DeviceInfo {
		if item.ID == sb.ID {
			util.DeviceInfo[i].DtuReadWriteCloser = port //把连接类写入变量
		}
	}
	error = false
	return
}

func DTUConnect(sb models.DeviceInfo) {
	buffer := make([]byte, 0)
	Port, err := OpenUart(sb)
	if !err {
		receivedData := false // 标志是否收到数据
		go func() {
			for {
				time.Sleep(50 * time.Millisecond)
				buf := make([]byte, 5)
				//var buf []byte
				n, err := Port.Read(buf)
				if err != nil {
					if err != io.EOF {
						fmt.Println("EOF0")
						return
					}
					break
				} else {
					if n == 0 {
						if receivedData {
							//成功接收
							fmt.Printf("%s\n", buffer)
							fmt.Println("buffer", buffer)
							SendDataByte(buffer, sb)
							buffer = make([]byte, 0) // 重置 buffer
							receivedData = false
						}
					} else {
						receivedData = true
						buf = buf[:n]
						buffer = append(buffer, buf...)
					}
				}
			}
		}()

	}
}
